package com.example.splash

import android.R.color
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.example.splash.databinding.ActivityMainBinding
import com.example.splash.font.FontHelper
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.OffsetEdgeTreatment
import com.google.android.material.shape.RoundedCornerTreatment
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.android.material.shape.ShapePath
import com.google.android.material.shape.TriangleEdgeTreatment
import java.lang.reflect.Field


class MainActivity : BaseAc() {

    companion object{
        const val  TAG = "MainActivity"
    }

    private lateinit var mBinding:ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        mBinding.bar.setOnSeekBarChangeListener(object :OnSeekBarChangeListener{
            
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                Log.d(TAG, "onProgressChanged: $progress")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                
            }

        })
        
        
        fontTest()

        mBinding.text5.postDelayed({
            showShape2(mBinding.text3,mBinding.imageView1)
            showShape2(mBinding.text4,mBinding.imageView3)
            showShape2(mBinding.text5,mBinding.imageView2)
        },500)



        mBinding.one.setOnClickListener {
            //openAppSettings(this)
            startActivity(Intent(this,Page2::class.java))
        }

        mBinding.two.setOnClickListener {
            requestWriteSettingsPermission(this)
        }

        mBinding.three.setOnClickListener {
            requestOverlayPermission(this)
        }

        mBinding.four.setOnClickListener {
            andB(this)
        }

        replaceColorField("component_color_theme", R.color.component_color_theme_b)

    }


    private fun showShape(view:TextView){
        // 代码设置 聊天框效果
        val shapeAppearanceModel3 = ShapeAppearanceModel.builder().apply {
            setAllCorners(RoundedCornerTreatment())
            setAllCornerSizes(20f)

            val height =view.measuredHeight

            val size = 20F


            val centers = height/2f-size
            setLeftEdge(object : TriangleEdgeTreatment(size, false) {
                // center 位置 ， interpolation 角的大小
                override fun getEdgePath(length: Float, center: Float, interpolation: Float, shapePath: ShapePath) {
                    super.getEdgePath(length, centers, interpolation, shapePath)
                }
            })
        }.build()

        val drawable3 = MaterialShapeDrawable(shapeAppearanceModel3).apply {
            setTint(ContextCompat.getColor(this@MainActivity, R.color.black))
            paintStyle = Paint.Style.FILL
        }
        (view.parent as ViewGroup).clipChildren = false // 不限制子view在其范围内
        view.setTextColor(Color.WHITE)
        view.background = drawable3
    }


    private fun showShape2(view: TextView,modelView:View,type:Int=0){

        val modelViewH = modelView.height
        val modelViewCenter = modelViewH/2f

        val viewH = view.height
        val viewCenter =  viewH/2f

        val size = 20F

        val offset  =  if (viewH>modelViewH){
            -viewCenter + modelViewCenter
        }else{
            0f
        }

        val offsetEdgeTreatment = OffsetEdgeTreatment(
            TriangleEdgeTreatment(size, false),
            offset
        )

        val shapeModel = ShapeAppearanceModel.builder().setAllCornerSizes(20f)
        if (type==0) shapeModel.setLeftEdge(offsetEdgeTreatment) else shapeModel.setRightEdge(offsetEdgeTreatment)
        val build = shapeModel.build()
        val backgroundDrawable = MaterialShapeDrawable(build).apply {
            paintStyle = Paint.Style.FILL_AND_STROKE
        }
        val tintColor = if (type == 0) Color.WHITE else Color.parseColor("#9AE450")
        backgroundDrawable.setStroke(5f,Color.parseColor("#D6D6D6"))
        backgroundDrawable.setTint(tintColor)
        (view.parent as ViewGroup).clipChildren = false
        view.setTextColor(Color.BLACK)
        view.background = backgroundDrawable
    }



    /**
     * 小:0.9        0.86
     * 默认：1.0     1.0
     * 中：1.15     1.05
     * 大号：1.35   1.25
     * 超大：1.6    1.4
     */
    private fun fontTest() {
        val fontSize = FontHelper.getFontSize(this)
        Log.d(TAG, "fontTest: fontSize:$fontSize")
    }


    private fun openAppSettings(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:${context.packageName}")
        context.startActivity(intent)
    }


    private fun requestWriteSettingsPermission(context: Context) {
        if (!Settings.System.canWrite(context)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_WRITE_SETTINGS,
                Uri.parse("package:${context.packageName}")
            )
            context.startActivity(intent)
            Toast.makeText(context, "请授予修改系统设置权限", Toast.LENGTH_SHORT).show()
        }
    }

    private fun requestOverlayPermission(context: Context) {
        if (!Settings.canDrawOverlays(context)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:${context.packageName}")
            )
            context.startActivity(intent)
            Toast.makeText(context, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show()
        }
    }

    private fun andB(context: Context){
        requestWriteSettingsPermission(context)
        requestOverlayPermission(context)
    }


    fun replaceColorField2(colorName: String, newColorValue: Int) {
        try {
            // 获取 Color 类的指定静态字段
            val field: Field = R.color::class.java.getField(colorName)
            // 设置字段为可访问
            field.isAccessible = true
            // 替换静态字段的值（null 表示静态字段）
            field.setInt(null, newColorValue)
            // 验证替换是否成功
            val updatedColor = field.getInt(null)
            val color = ContextCompat.getColor(this, R.color.component_color_theme)
            mBinding.one.setTextColor(color)
            Log.d(TAG, "replaceColorField: Updated $colorName value: $updatedColor")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d(TAG, "replaceColorField: $e")
        }
    }

}